package reno.activity.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reno.activity.common.JsonUtils;
import reno.activity.eo.ActivityEntity;
import reno.activity.mo.*;
import reno.activity.service.ActivityService;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@SuppressWarnings("AlibabaAvoidPatternCompileInMethod")
@RestController
public class ActivityController {

    private static final Pattern BAN = Pattern.compile("^BAN.+$");

    @Autowired
    ActivityService activityService;

    @PostMapping(value = "/joinActivity")
    public JSONObject joinActivity(@RequestBody JoinActivityMO joinActivityMO) {
        List<Reward> rewards = RewardPool.getInstance().getRewardPoolMap().get(joinActivityMO.getActivityid());
        if (rewards == null || rewards.size() == 0) {
            return JsonUtils.failure("活动已经结束");
        }
        ActivityEntity activityEntity = ActivityPool.getInstance().getActivityPoolMap().get(joinActivityMO.getActivityid());
        if (rewards == null || rewards.size() == 0 || activityEntity == null || !activityEntity.isOpen()) {
            return JsonUtils.failure("该活动暂未开启");
        }
        String groupLimit = activityEntity.getGroupcardlimit();
        Pattern pattern = null;
        if (groupLimit != null && groupLimit.length() > 0) {
            pattern = Pattern.compile(groupLimit);
        }
        //判断是否有抽奖资格（群名片，是否已中奖）
        Reward resultReward = null;
        RewardPool rewardPool = RewardPool.getInstance();
        Map<Long, Map<Long, Reward>> rewardResultMap = rewardPool.getRewardResultMap();
        Map<Long, Reward> rewardMap = rewardResultMap.get(joinActivityMO.getActivityid());
        boolean alreadywon = rewardMap.get(joinActivityMO.getJoinQQ()) == null;
        GroupCardPool groupCardPool = GroupCardPool.getInstance();
        String card = groupCardPool.getGroupMap().get(joinActivityMO.getGroupid()).get(joinActivityMO.getJoinQQ()).getCard();
        if (card == null) {
            card = "null";
        }
        if (!(pattern != null && pattern.matcher(card).matches())) {
            return JsonUtils.failure("您的群名片格式不符合要求，活动开始时您的群名片为" + card);
        } else if (!alreadywon) {
            return JsonUtils.failure("您已中奖，请勿重复抽取[CQ:at,qq=FROMQQ]".replace("FROMQQ", String.valueOf(joinActivityMO.getJoinQQ())));
        } else if (pattern.matcher(card).matches()) {
            //若有资格，则进行抽奖
            Collections.shuffle(rewards);
            resultReward = rewards.get(0);
            rewards.remove(0);
            RewardPool.getInstance().getRewardPoolMap().put(joinActivityMO.getActivityid(), rewards);
            resultReward.setWinnerQQ(joinActivityMO.getJoinQQ());
            resultReward.setWinnerCard(card);
            if (!BAN.matcher(resultReward.getRewardname()).matches()) {
                RewardPool.getInstance().getRewardResultMap().get(joinActivityMO.getActivityid()).put(joinActivityMO.getJoinQQ(), resultReward);
            }
            return JsonUtils.success(resultReward);
        } else {
            return JsonUtils.failure("未知错误");
        }
        //返回抽奖结果
    }

    @PostMapping(value = "/startActivity")
    public JSONObject startActivity(@RequestBody ActivitySwitchMO activitySwitchMO) {
        ActivityEntity activityEntity = activityService.getActivityInfo(activitySwitchMO.getActivityid());
        String[] splitAuth = activityEntity.getManager().split("\\|");
        List<String> authList = Arrays.asList(splitAuth);
        if (!authList.contains(activitySwitchMO.getRequestQQ().toString())) {
            return JsonUtils.failure("您无此权限");
        }
        if (activitySwitchMO.getMemberList() == null || activitySwitchMO.getMemberList().size() == 0) {
            return JsonUtils.failure("请传入群成员列表");
        }
        GroupCardPool groupCardPool = GroupCardPool.getInstance();

        groupCardPool.getGroupMap().put(activitySwitchMO.getGroupid(), activityService.buildGroupCardMap(activitySwitchMO.getMemberList()));
        String result = activityService.buildActivity(activitySwitchMO.getActivityid());
        if (result != null) {
            return JsonUtils.success(result);
        } else {
            return JsonUtils.failure("未查询到活动详细配置，活动开启失败");
        }
    }

    @PostMapping(value = "/stopActivity")
    public JSONObject stopActivity(@RequestBody ActivitySwitchMO activitySwitchMO) {
        if (!activityService.checkAuth(activitySwitchMO)) {
            return JsonUtils.failure("您无此权限");
        }
        ActivityEntity activityEntity = ActivityPool.getInstance().getActivityPoolMap().get(activitySwitchMO.getActivityid());
        if (activityEntity == null) {
            return JsonUtils.failure("活动" + activityEntity.getActivityname() + "尚未开始");
        }
        activityEntity.setOpen(false);
        ActivityPool.getInstance().getActivityPoolMap().put(activitySwitchMO.getActivityid(), activityEntity);
        ActivityPool.getInstance().getActivityPoolMap().put(activitySwitchMO.getActivityid(), null);
        List<Reward> rewardList = RewardPool.getInstance().getRewardPoolMap().get(activitySwitchMO.getActivityid());
        activityService.writeFile(rewardList, activitySwitchMO.getActivityid().toString());
        RewardPool.getInstance().getRewardPoolMap().put(activitySwitchMO.getActivityid(), null);
        Map<Long, Reward> rewardMap = RewardPool.getInstance().getRewardResultMap().get(activitySwitchMO.getActivityid());
        activityService.writeFile(rewardMap, activitySwitchMO.getActivityid().toString());
        RewardPool.getInstance().getRewardResultMap().put(activitySwitchMO.getActivityid(), null);
        return JsonUtils.success("活动[" + activityEntity.getActivityname() + "]已关闭");
    }

    @PostMapping(value = "/getActivityResult")
    public JSONObject getActivityResult(@RequestBody ActivitySwitchMO activitySwitchMO) {
        if (!activityService.checkAuth(activitySwitchMO)) {
            return JsonUtils.failure("您无此权限");
        }
        Map<Long, Reward> rewardMap = RewardPool.getInstance().getRewardResultMap().get(activitySwitchMO.getActivityid());
        if (rewardMap == null) {
            return JsonUtils.failure("该活动暂未开启。");
        } else if (rewardMap.size() == 0) {
            return JsonUtils.failure("暂时无人中奖。");
        }
        String activityResult = activityService.rewardMapToString(rewardMap);
        return JsonUtils.success(activityResult);
    }

    @PostMapping(value = "/pauseActivityResult")
    public JSONObject pauseActivityResult(@RequestBody ActivitySwitchMO activitySwitchMO) {
        if (!activityService.checkAuth(activitySwitchMO)) {
            return JsonUtils.failure("您无此权限");
        }
        ActivityEntity activityEntity = ActivityPool.getInstance().getActivityPoolMap().get(activitySwitchMO.getActivityid());
        if (activityEntity == null) {
            return JsonUtils.failure("该活动暂未开启.");
        }
        if (activityEntity.isOpen()) {
            activityEntity.setOpen(false);
            return JsonUtils.success("活动[" + activityEntity.getActivityname() + "]暂停成功");
        } else {
            return JsonUtils.failure("该活动暂未开启。");
        }
    }

    @PostMapping(value = "/continueActivityResult")
    public JSONObject continueActivityResult(@RequestBody ActivitySwitchMO activitySwitchMO) {
        if (!activityService.checkAuth(activitySwitchMO)) {
            return JsonUtils.failure("您无此权限");
        }
        ActivityEntity activityEntity = ActivityPool.getInstance().getActivityPoolMap().get(activitySwitchMO.getActivityid());
        if (activityEntity == null) {
            return JsonUtils.failure("该活动暂未开启.");
        }
        if (!activityEntity.isOpen()) {
            activityEntity.setOpen(true);
            return JsonUtils.success("活动[" + activityEntity.getActivityname() + "]继续成功");
        } else {
            return JsonUtils.failure("该活动正在进行。");
        }
    }



}
